//
//  TraineeTable.m
//  TMS
//
//  Created by Dhanashree Bodas on 28/01/15.
//  Copyright (c) 2015 Dhanashree Bodas. All rights reserved.
//

#import "TraineeTable.h"

@implementation TraineeTable


-(int) addTrainee:(NSString *)fname andLname:(NSString *)lname andEmail:(NSString *)email andPassword:(NSString *)pswd
{
    self.db=[[DBManager alloc] initWithDatabaseFilename:@"tmsdb.sql"];
    
    NSString *query=[NSString stringWithFormat:@"insert into Trainee(firstname,lastname,password,email) values('%@','%@','%@','%@')",fname,lname,pswd,email];
    
       [self.db executeQuery:query];
    if(self.db.affectedRows!=0)
        return 1;
    return 0;
}

-(NSArray *) listTrainee{
   self.db=[[DBManager alloc]initWithDatabaseFilename:@"tmsdb.sql"];
    
    NSString *query=@"select * from Trainee";
    
    NSArray *traineeData=[self.db loadDataFromDB:query];
    
    NSMutableArray *tdata = [[NSMutableArray alloc] init];
    
    for(int i=0;i<traineeData.count;i++)
    {
        Trainee *t=[[Trainee alloc]init];
        id temp = [traineeData objectAtIndex:i];
        t.tid = [[temp objectAtIndex:[self.db.arrColumnNames indexOfObject:@"tid"] ] intValue];
        t.fname=[temp objectAtIndex:[self.db.arrColumnNames indexOfObject:@"firstname"]];
        t.lname=[temp objectAtIndex:[self.db.arrColumnNames indexOfObject:@"lastname"]];
        t.email=[temp objectAtIndex:[self.db.arrColumnNames indexOfObject:@"email"]];
        t.password=nil;
        [tdata addObject:t];
    }
    return tdata;
}



-(int) deleteTrainee:(int)tid
{
    
    self.db=[[DBManager alloc] initWithDatabaseFilename:@"tmsdb.sql"];
    
    NSString *query=[NSString stringWithFormat:@"delete from Trainee where tid='%d'",tid];
    
    [self.db executeQuery:query];
    
    if(self.db.affectedRows!=0)
        return 1;
    return 0;

}


//Trainee Module

-(int) Login:(NSString *)username andPassword:(NSString *)pswd
{
    
    NSString *query=[NSString stringWithFormat:@"select tid from Trainee where email='%@'",username];
    
    self.db=[[DBManager alloc] initWithDatabaseFilename:@"tmsdb.sql"];
    
    NSArray *traineedata=[[NSArray alloc] init];
    traineedata=[self.db loadDataFromDB:query];
    
    if(traineedata.count>0)
    {
        
        int tid=[[[traineedata objectAtIndex:0] objectAtIndex:[self.db.arrColumnNames indexOfObject:@"tid"]] intValue];
        NSLog(@"Trainee id %d",tid);
        return tid;
    }
    else
    {
        NSLog(@"No trainee available");
        return 0;
        
    }
}

@end
